<?php
namespace app\api\server\index;
use app\api\model\user\UserCancelModel;
use app\logic\model\user\UserLogicModel;
use app\logic\single\WechatSingle;
use think\Request;
use app\api\model\UserModel as UserModel;
use app\api\ServerBase;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Session;
use think\facade\Cookie;
use think\facade\Db;
use app\api\common;
use think\facade\Log;
use app\logic\traits\Token;
use think\cache\driver\Redis;

class Login extends ServerBase{
    use Token;
	protected $request;
	protected static $model;
    /**
     * @var mixed
     */
    private $appid;
    /**
     * @var mixed
     */
    private $appsecret;
    use Token;
    public function __construct(Request $request)
    {
        $this->request = $request;
        self::$model=new UserModel();
        $this->appid = config('wechat.appid');
        $this->appsecret = config('wechat.secret');
    }
    public function getCode(){
    	$data=$this->request->param();

        $r=common::get_code($data['mobile'],$type=0);
        if($r['result']!=1){
        	$this->getMessageCode('adminMessage.send.sendCodeErrror',1);
        	$this->error.=$r['error'];
        	return false;
        }
        if(isset($data['type']) && $data['type']==1){
        	common::addCodeSendNumber($data['mobile']);
        }
        $this->getMessageCode('adminMessage.send.sendCodeSuccess',2);
        return true;
    }
    
    public function checkLogin(){
    	$data=$this->request->param();
        if(!Cache::get($data['mobile']."code")){
        	$this->getMessageCode('adminMessage.send.getCode',1);
    		return false;
        }
        if(Cache::get($data['mobile'].'code_time')<time()-(config('adminMessage.send.codeTime.time'))){
    		$this->getMessageCode('adminMessage.send.codeTime',1);
    		return false;
    	}
    	if($data['code']!=Cache::get($data['mobile'].'code')){
			$this->getMessageCode('adminMessage.send.codeTrue',1);
			return false;
		}
        return true;
    }
    
    
    //登陆
    public function login(){
    	$data=$this->request->param();
    	//if(!$this->checkLogin()) return false;
    	//1.检测当前手机号是否已绑定其他手机
    	$user=self::$model->findUser(['mobile'=>$data['mobile']],"id,openid,mobile,is_black");

    	//3.未注册自动注册
    	if(!$user){
    		$user=$this->register($data);
    	}else{
            if(isset($data['openid'])){
                self::$model->where('id',$user['id'])->save(['openid'=>$data['openid']]);
            }
        }
    	if(!$user){
    		return false;
    	}
        if($user['is_black'] == 1){
            $this->ERROR='在黑名单中，不能登录';
            return false;
        }
    	$token = $this->CreateToken($user['mobile']);
    	$this->getMessageCode('adminMessage.success.select',2);
    	return $token;
    }
    
    //绑定手机事情即默认注册
    public function register($data){
    	$user=[
    		"openid"=> $data['openid'] ?? '',
    		'pid'=> $data['pid'] ?? '',
    		'nickname'=> $data['nickname'] ?? '',
    		'head_img'=> $data['headimgurl'] ?? config('app.site_url').'storage/default_head_img.png',
    		'mobile'=>$data['mobile'],
    		'create_time'=>date('Y-m-d H:i:s'),
    	];
    	$user_id=self::$model->insertUser($user);
    	if(!$user_id){
    		$this->getMessageCode('adminMessage.wechatLogin.registerError',1);
    		return false;
    	}
    	return $user;
    }


    public function getOpenid(){
        $code = $this->request->post('code')??'';
        if(empty($code)) {
            $this->getMessageCode('code_common.illegal', 1);
            return false;
        }
        $wechat_user = WechatSingle::getInstance()->getOpenidByCode($code);
        if(is_array($wechat_user)){
            //返回数组才是对的
            $this->getMessageCode('adminMessage.success.select',0);
            return $wechat_user['openid'];
        }else{
            //code在上面就判断了，所以不会拿到false
            $this->getMessageCode('adminMessage.error.select',1);
            return $wechat_user;
        }
    }
    public function loginByOpenid(){
        $openid = $this->request->post('openid')??'';
        if(empty($openid)) {
            $this->getMessageCode('code_common.illegal', 1);
            return false;
        }
        $user= UserLogicModel::getInfoByOpenid($openid);
        if(empty($user) || empty($user['mobile'])){
            //没有用户信息，或者没有绑定手机号，都返回未注册
            $this->getMessageCode('adminMessage.user.notMobile',1);
            $token=false;
        }else{
            $this->getMessageCode('adminMessage.success.select',2);
            $token = $this->CreateToken($user['mobile']);
        }
        return $token;
    }
  	
}
